import React from "react";
import { connect } from "react-redux";
import "./createclubdialog.less";
import classnames from "classnames";

const mapStateToProps = state => {
  return {
    userInfo: state.app.userInfo,
    currentGame: state.group.chooseCreateGame
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    chooseCreateGame: msg =>
      dispatch(global.allActions.groupActions.chooseCreateGame(msg)),
    ruleConfClicked: (index, value) =>
      dispatch(
        global.allActions.groupActions.ruleConfClicked({ index, value })
      ),
    createGame: alias =>
      dispatch(global.allActions.groupActions.createGame(alias))
  };
};

class CreateClubDialog extends React.Component<any, any> {
  public constructor(props) {
    super(props);
    this.state = {
      step: 1,
      inviteId: "",
      tip: "",
      querySuccess: false,
      serverSideGroup: undefined,
      otherPayDialog: false,
      otherPayType: false,
      bigWinner: 1,
      otherPlayers: 1
      // currentGame: {}
    };
  }

  public componentWillMount() {
    // let game = sessionStorage.getItem('ClubGame');
    // let currentGame = ClubConfig.filter((item)=>{
    //   return item.name ==  game.split('#')[1]
    // })[0];
    // this.setState({
    //   currentGame
    // });
  }
  public componentWillUnmount() {
    // this.props.chooseCreateGame()
  }
  public focusIpt() {
    // if (document.getElementById('rule-ipt')) {
    //   document.getElementById('rule-ipt').focus()
    // }
  }

  public queryInvite() {
    if (this.state.inviteId.length === 0) {
      this.setState({ tip: "请输入俱乐部ID" });
    } else {
      this.setState({ tip: "" });
      const url = `${config.pre}/crowd/info/${Cookies.get("areaCode")}/${
        this.state.inviteId
      }`;
      const opt = { method: "GET" };
      fetchJson(url, opt).then(data => {
        console.log(data);
        if (data.result) {
          this.setState({ tip: data.message, querySuccess: false });
          return;
        }
        this.setState({
          tip: "俱乐部名称: " + data.data.crowdName,
          querySuccess: true,
          serverSideGroup: data.data
        });
      });
    }
  }

  public join() {
    if (!this.state.querySuccess) {
      this.setState({ tip: "请先查询俱乐部" });
      return;
    }
    const send = {
      crowdId: this.state.serverSideGroup.id,
      applyId: this.props.userInfo.uid
    };
    console.log("send", send);
    const url = `${config.pre}/crowd/relation/${Cookies.get("areaCode")}`;
    const opt = { method: "POST", body: JSON.stringify(send) };
    fetchJson(url, opt).then(data => {
      if (data.result) {
        this.setState({ tip: data.message, step: 2 });
        return;
      }
      this.setState({ tip: data.message, step: 2 });
    });
  }

  public handleRuleIdChange(e) {
    this.setState({ inviteId: e.target.value, querySuccess: false });
  }

  confirm() {
    console.log("confirm!!");
  }

  private onCreateConf() {
    console.log(this.state);
  }

  parseJSON(params: string) {
    let json = null;
    try {
      json = JSON.parse(params);
    } catch (error) {
      console.log(error);
      json = "error";
    }
    return json;
  }

  private gameAliasChange(e) {
    this.setState({ gameAlias: _.trim(e.target.value) });
  }

  private showOtherPaytypes() {
    this.setState({otherPayDialog: true})
  }

  private changePaytypeRatio(type, ratio) {
    console.log(type, ratio)
    if(this.state.otherPayType) {
      if(type === 1) {
        let bw = this.state.bigWinner;
        if(bw + ratio <= 0) {
          return
        }
        this.setState({
          bigWinner: bw + ratio
        })
      } else {
        let op = this.state.otherPlayers;
        if(op + ratio <= 0) {
          return
        }
        this.setState({
          otherPlayers: op + ratio
        })
      }
    }
    
  }

  public render() {
    const { currentGame, ruleConfClicked, createGame } = this.props;
    const circleCn = classnames({
      "choose-circle-small": currentGame.config.options.length >= 7,
      "choose-circle": currentGame.config.options.length < 7
    });
    const { gameAlias, otherPayDialog, otherPayType, bigWinner, otherPlayers } = this.state;
    var tipText = this.parseJSON(currentGame.hintJson);
    if (tipText == "error") {
      if (
        currentGame.gameName === "经典斗牛" ||
        currentGame.gameName === "点子牛"
      ) {
        tipText = [
          "温馨提示:",
          "扣钻方式: 至少打完一回合,产生战绩后才扣钻",
          "中途加入: AA支付时,从第十六回合后的中途加入扣钻一个"
        ];
      } else if (currentGame.gameName === "斗公牛") {
        tipText = [
          "温馨提示:",
          "扣钻方式: 至少打完一回合,产生战绩后才扣钻",
          "中途加入: AA支付时,从第二轮开始后的中途加入扣钻一个"
        ];
      } else if (currentGame.gameName === "欢乐金花") {
        tipText = [
          "温馨提示:",
          `中途加入: AA支付时,玩家在回合过半后加入,扣钻数减半`
        ];
      } else {
        tipText = ["温馨提示:", `扣钻方式: 第一回合打完,产生战绩后才扣钻`];
      }
    }
    const createBtnCls = classnames({
      "rule-row": true,
      btn: true,
      "small-gap": currentGame.config.options.length > 9
    });
    const modalClass = classnames({
      "modal-wrapper club-modal": true,
      "is-android": !!window.navigator.appVersion.match(/Android/i)
    });

    let  paytypeImgC= otherPayType
                        ? `img/createGame/circle-active.png?v=20181201`
                        : `img/createGame/circle-default.png?v=20181201`;
    let  paytypeImgB = otherPayType
                        ? `img/createGame/circle-default.png?v=20181201`
                        : `img/createGame/circle-active.png?v=20181201`;
    return (
      <div className="create-game-base">
        <img
          className="full pos-abs create-club-bg"
          src="./img/createGame/create-game-di.png?v=20181201"
          alt=""
        />
        <div className="full pos-abs modal">
          <div className="full-width club-title-wrapper">
            <img
              className="create-club-title"
              src="img/club/create-club-title.png?v=20181201"
              alt=""
            />
            <img
              onClick={this.props.close.bind(this)}
              className="close"
              src="img/createGame/close-btn.png?v=20181201"
              alt=""
            />
          </div>

          <div className={modalClass}>
            <div className="pure-g rule-row">
              <div className="pure-u-7-24">
                <span className="rule-name color-blue">俱乐部名称</span>
              </div>
              <div className="pure-u-17-24">
                <input
                  className="color-brown method-input"
                  type="text"
                  value={gameAlias}
                  onChange={this.gameAliasChange.bind(this)}
                  maxlength="10"
                />
              </div>
            </div>
            {currentGame.config.options.map((cData, index) => {
              if (cData._visible === false) {
                return;
              }
              const rowCn = classnames({
                "rule-row": true,
                "pure-g": true,
                "large-gap": currentGame.config.options.length <= 5,
                "small-gap": currentGame.config.options.length > 9
              });
              const half = cData.choice.some(
                choice => choice.label.length >= 10
              );
              {
                /*console.log(cData)*/
              }
              const halfRulename = cData.name.length >= 6;
              const choiceCn = classnames({
                "pure-u-3-4": true,
                "pure-g": true,
                choice: true,
                "half-font": half
              });
              const ruleCn = classnames({
                "rule-name color-blue": true,
                "half-font": halfRulename
              });
              let threeChoices =
                cData.choice.length == 3 ? "pure-u-1-3" : "pure-u-1-2";
              if (cData.name == "局数") {
                threeChoices = "pure-u-1-2";
              }

              if (cData.name == "支付方式") {
                threeChoices = "pure-u-1-2";
              }

              if (cData.key === "maxBetPoint") {
                if (
                  currentGame.gameName == "经典斗牛" ||
                  currentGame.gameName == "点子牛" ||
                  currentGame.gameName == "斗公牛"
                ) {
                  const maxMultiple = currentGame.config.options.find(
                    con => con.name === "固定倍数"
                  );
                  if (maxMultiple) {
                    if (maxMultiple.selected[0] !== -1) {
                      return;
                    }
                  }
                }
              }
              if (cData.key === "autoOnAccord") {
                if (
                  currentGame.gameName == "经典斗牛" ||
                  currentGame.gameName == "点子牛" ||
                  currentGame.gameName == "斗公牛"
                ) {
                  const maxMultiple = currentGame.config.options.find(
                    con => con.name === "固定倍数"
                  );
                  if (maxMultiple) {
                    if (maxMultiple.selected[0] === -1) {
                      return;
                    }
                  }
                }
              }

              if (cData.show === "hide" ) {
                return null;
              }

              if (cData.key == "matchType") {
                threeChoices = "pure-u-1-1";
              }

              return (
                <div className={rowCn} key={index}>
                  <div className="pure-u-1-4">
                    <span className={ruleCn}>{cData.name}</span>
                  </div>
                  <div className={choiceCn}>
                    {cData.choice.map((choice, choiceInd) => {
                      let multiImgSrc = cData.muti ? "rect" : "circle";
                      // let multiImgSrc = 'circle'
                      const selected = cData.selected.some(
                        select => select === choice.value
                      );
                      const imgSrc = selected
                        ? `img/createGame/${multiImgSrc}-active.png?v=20181201`
                        : `img/createGame/${multiImgSrc}-default.png?v=20181201`;
                      const textCn = classnames({
                        "choose-text": true,
                        orange: selected
                      });
                      // 如果是turns
                      var append = "";
                      if (cData.key === "turns") {
                        const payTypeChoice = currentGame.config.options.find(
                          con => con.name === "支付方式"
                        );

                        let showPay = currentGame.config.payTypeInfo.find(
                          info => info.value === payTypeChoice.selected[0]
                        );
                        if (currentGame.gameName == "跑得快") {
                          const pNum = currentGame.config.options.find(
                            con => con.name === "人数"
                          );
                          if (
                            pNum.selected[0] == 3 &&
                            payTypeChoice.selected[0] == 2
                          ) {
                            showPay = currentGame.config.payTypeInfo[2];
                          }
                        }
                        if (
                          currentGame.gameName == "经典斗牛" ||
                          currentGame.gameName == "点子牛" ||
                          currentGame.gameName == "斗公牛"
                        ) {
                          const pNum = currentGame.config.options.find(
                            con => con.name === "最大人数"
                          );
                          if (
                            pNum.selected[0] == 10 &&
                            payTypeChoice.selected[0] == 2
                          ) {
                            showPay = currentGame.config.payTypeInfo[2];
                          }
                        }
                        const showData = showPay.choice.find(
                          show => show.id === choice.value
                        );
                        append = showData.data;
                      }

                      return (
                        <div
                          className={threeChoices}
                          key={choiceInd}
                          onClick={ruleConfClicked.bind(
                            this,
                            index,
                            choice.value
                          )}
                        >
                          <img src={imgSrc} className={circleCn} alt="" />
                          <span className={textCn}>
                            {(choice.label + append).replace('群主','会长')}
                          </span>
                          
                        </div>
                      );
                    })}
                    {
                      /*cData.key === 'payType' ? <div className="pure-u-1-3" onClick={this.showOtherPaytypes.bind(this)}>
                      <img
                        src="img/club/other-paytypes.png?v=20181201"
                        className=" other-paytypes"
                        alt=""
                        />
                      </div> : null*/
                    }
                  </div>
                  <img
                    src="img/app/create-line.png?v=20181201"
                    className="rule-bottom-line"
                    alt=""
                  />
                </div>
              );
            })}
            <div className={createBtnCls}>
              <div className="start-game-btn" onClick={createGame.bind(this, {alias: gameAlias, bigWinner,otherPlayers, otherPayType})} />
            </div>
            {/* <div className="rule-row club-tip-wrapper">
              {tipText.map((text, index) => (
                <p key={index} className="club-tip">
                  {text}
                </p>
              ))}
            </div> */}
          </div>
        </div>

        {
          otherPayDialog ? <div className="other-paytypes-dialog">
            <div className="paytypes-content pure-g">
              <div class="pure-u-1-2 align-center">
                <img src={paytypeImgB} class="choose-circle" alt="" onClick={()=>{ this.setState({otherPayType: false}) }}/>
                <span>会长支付</span>
              </div>
              <div class="pure-u-1-2 align-center">
                <img src={paytypeImgC} class="choose-circle" alt=""  onClick={()=>{ this.setState({otherPayType: true}) }}/>
                <span>自定义支付</span>
              </div>

              <div className="pure-g full-width paytype-wrapper">
                <div className="pure-u-1-2 paytype-ratio-change">
                  <span className="paytype-ratio-name">大赢家</span>
                  <img src="img/club/minus.png?v=20181201" alt="" className="paytype-ratio-btn" onClick={this.changePaytypeRatio.bind(this, 1, -1)}/>
                  <span>{bigWinner}</span>
                  <img src="img/club/plus.png?v=20181201" alt="" className="paytype-ratio-btn" onClick={this.changePaytypeRatio.bind(this, 1, 1)}/>
                </div>
                <div className="pure-u-1-2 paytype-ratio-change">
                  <span className="paytype-ratio-name">其他玩家</span>
                  <img src="img/club/minus.png?v=20181201" alt="" className="paytype-ratio-btn" onClick={this.changePaytypeRatio.bind(this, 2, -1)}/>
                  <span>{otherPlayers}</span>
                  <img src="img/club/plus.png?v=20181201" alt="" className="paytype-ratio-btn" onClick={this.changePaytypeRatio.bind(this, 2, 1)}/>
                </div>
              </div>
              <div className="pure-g paytype-actions-wrapper">
                <div className="pure-u-1-2">
                  <img src="img/club/confirm.png?v=20181201" alt="" className="paytype-actions" onClick={()=>{ this.setState({otherPayDialog: false }) }}/>
                </div>
                <div className="pure-u-1-2">
                  <img src="img/club/cancel.png?v=20181201" alt="" className="paytype-actions" onClick={()=>{ this.setState({otherPayDialog: false, bigWinner: 1, otherPlayers: 1}) }}/>
                </div>
              </div>
            </div>
          </div> : null
        }
      </div>
    );
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CreateClubDialog);
